package com.example.bee_work_3.account;

import android.content.SharedPreferences;
import android.util.Log;

import com.example.bee_work_3.net_request.WS;

public class LoginOrRegister {

    private SharedPreferences userdata;
    private WS.CallBack callBack;
    public static final String COOKIESNAME = "android";

    public LoginOrRegister(SharedPreferences userdata, WS.CallBack callBack) {
        this.userdata = userdata;
        this.callBack = callBack;
    }

    public void login(String user, String password) {
        String[][] param = new String[][]{
                {"username", user},
                {"password", password}
        };
        WS.load("https://www.wanandroid.com/user/login")
                .addParam(param)
                .addCallBack(callBack)
                .saveCookies(COOKIESNAME)
                .post();
    }

    public void logout() {
        WS.load("https://www.wanandroid.com/user/logout/json")
                .addCallBack(callBack)
                .get();
        SharedPreferences.Editor editor = userdata.edit();
        editor.remove("username");
        editor.remove("password");
        editor.apply();
    }

    public void register(final String name, final String password) {
        String[][] param = new String[][]{
                {"username", name},
                {"password", password},
                {"repassword", password}
        };
        WS.load("https://www.wanandroid.com/user/register")
                .addCallBack(callBack)
                .addParam(param)
                .saveCookies(COOKIESNAME)
                .post();
    }

    public boolean autoLogin() {
        String username = userdata.getString("username", "");
        String password = userdata.getString("password", "");
        Log.e("autologin", username + "\n" + password);
        if ((!username.equals("")) && (!password.equals(""))) {
            login(username, password);
            return true;
        }
        return false;
    }

    public void saveData(String name, String password) {
        SharedPreferences.Editor editor = userdata.edit();
        editor.clear();
        editor.putString("username", name);
        editor.putString("password", password);
        editor.apply();
    }
}
